package com.yuzhi.fine.popupwindow;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn1 = findViewById(R.id.btn_1);
        Button btn2 = findViewById(R.id.btn_2);
        Button btnUpdate = findViewById(R.id.btn_update);
        Button btnDismiss = findViewById(R.id.btn_dismiss);

        TestPopupWindow popupWindow = new TestPopupWindow(this);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        btn1.setOnClickListener(v -> {
            int height = 0;
            if(checkDeviceHasNavigationBar(MainActivity.this)) {
                Toast.makeText(this, "NavBarHeight = " + getNavigationBarHeight(MainActivity.this), Toast.LENGTH_SHORT).show();
                height = getNavigationBarHeight(MainActivity.this) + height;
            }
            popupWindow.showAtLocation(btn1, Gravity.BOTTOM, 0, height);
        });


        btn2.setOnClickListener(v -> {
            popupWindow.showAtLocation(btn1, Gravity.TOP, 0, 50);
        });

        btnUpdate.setOnClickListener(v -> {
            int testHeight = getNavigationBarHeight(MainActivity.this) + 100;
            if(Build.VERSION.SDK_INT < 24 || Build.VERSION.SDK_INT > 25 ) {
                popupWindow.update(0, testHeight, -1, -1, false);
            } else {
                // 7.0 和 7.1 版本 popupWindow.update存在系统bug，会造成Gravity丢失，变成Top|Left，所以位置会错误
                // 使用dismiss在show解决此bug
                popupWindow.dismiss();
                popupWindow.showAtLocation(btn1, Gravity.BOTTOM, 0, testHeight);
            }
            popupWindow.dismiss();
            popupWindow.showAtLocation(btn1, Gravity.BOTTOM, 0, testHeight);
        });

        btnDismiss.setOnClickListener(v -> popupWindow.dismiss());
    }


    class TestPopupWindow extends PopupWindow {

        TestPopupWindow(Context context) {
            super(context);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
            setOutsideTouchable(true);
            setFocusable(true);
            setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            View contentView = LayoutInflater.from(context).inflate(R.layout.popup_test, null, false);
            setContentView(contentView);
        }
    }


    /**
     * 获取虚拟功能键高度
     * @param context
     * @return
     */
    public int getNavigationBarHeight(Context context) {
        int height = 0;
        try {
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            if(windowManager != null) {
                Display display = windowManager.getDefaultDisplay();
                DisplayMetrics dm = new DisplayMetrics();
                Class c = Class.forName("android.view.Display");
                Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
                method.invoke(display, dm);
                height = dm.heightPixels - windowManager.getDefaultDisplay().getHeight();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return height;

    }

    /**
     * 获取是否存在NavigationBar，是否有虚拟按钮
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {

        }
        return hasNavigationBar;

    }

}
